package com.project.class8_23.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {
    public static void main(String[] args) {
        LockObj lockObj = new LockObj();
        new Thread(new Runnable() {
            @Override
            public void run() {
                lockObj.speak();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                lockObj.speak();
            }
        }).start();
    }
}

class LockObj{
    /**创建锁对象*/
    private Lock lockObject = new ReentrantLock();
    public void speak(){
        if(lockObject.tryLock()) {
            try {
                for (int i = 0; i < 10; i++) {
                    System.out.println(i);
                    Thread.sleep(100);

                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //释放锁
                lockObject.unlock();
            }
        }
        else{
            System.out.println("获得锁失败");
        }
    }
}